package server.startup;

import org.apache.catalina.*;
import org.apache.catalina.connector.http.HttpConnector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.loader.WebappClassLoader;
import org.apache.catalina.loader.WebappLoader;
import org.apache.naming.resources.ProxyDirContext;
import server.core.SimpleContextConfig;
import server.core.SimpleWrapper;

public class Bootstrap {
    public static void main(String[] args) {
        System.setProperty("catalina.base", System.getProperty("user.dir"));

        Wrapper wrapper1 = new SimpleWrapper();
        wrapper1.setName("Primitive");
        wrapper1.setServletClass("PrimitiveServlet");
        Wrapper wrapper2 = new SimpleWrapper();
        wrapper2.setName("Modern");
        wrapper2.setServletClass("ModernServlet");

        Context context = new StandardContext();
        context.setPath("/webapps/app1");
        context.setDocBase("/webapps/app1");

        context.addChild(wrapper1);
        context.addChild(wrapper2);

        context.addServletMapping("/Primitive", "Primitive");
        context.addServletMapping("/Modern", "Modern");

        LifecycleListener listener = new SimpleContextConfig();
        ((Lifecycle) context).addLifecycleListener(listener);
        context.setReloadable(true);

        Loader loader = new WebappLoader();
        context.setLoader(loader);

        Connector connector = new HttpConnector();
        connector.setContainer(context);
        try {
            connector.initialize();
            ((Lifecycle)connector).start();
            ((Lifecycle)context).start();
            //打印信息
            WebappClassLoader classLoader = (WebappClassLoader)loader.getClassLoader();
            System.out.println("Resources' docBase: " + ((ProxyDirContext)classLoader.getResources()).getDocBase());
            for (String s : classLoader.findRepositories()) {
                System.out.println("repository: " + s);
            }
            System.in.read();
            ((Lifecycle) context).stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
